package com.second.app.future;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

/**
 * @Author GYZ
 * <pre>
 *
 * </pre>
 */
public class AsynchronousTask implements Callable<Exception> {


    private CountDownLatch countDownLatch;

    private ExecutorService executorService;

    private Callable<Void> callable;

    public  AsynchronousTask(ExecutorService executorService, CountDownLatch countDownLatch, Callable<Void> callable) {
        this.executorService = executorService;
        this.countDownLatch = countDownLatch;
        this.callable = callable;
    }

    @Override
    public Exception call() {
        try {
            callable.call();
            return null;
        } catch (Exception e) {
            executorService.shutdownNow();
            while (countDownLatch.getCount() > 1) {
                countDownLatch.countDown();
            }
            return e;
        } finally {
            countDownLatch.countDown();
        }
    }
}
